map-macro
This crate offers declarative macros for initializing collections from the standard library.
This crate has zero dependencies.
Example
use hash_map;
let hello = hash_map! ;
Explicitly Typed Values for Trait Objects
As shown in the example above, the compiler uses type inference to infer the correct type for the created map. Unfortunately, type inference alone can not detect trait objects. This will not work, because the compiler is unable to figure out the right type:
use std::collections::HashMap;
use std::fmt::Debug;
use map_macro::hash_map;
let hello: HashMap<&str, &dyn Debug> = hash_map! {
"en" => &"Hello",
"de" => &"Hallo",
"fr" => &"Bonjour",
"es" => &"Hola",
};
The map_e!
macro enables you to use trait objects as values through
type coercion, making the example above compile successfully:
use HashMap;
use Debug;
use hash_map_e;
let hello: = hash_map_e! ;
Note that you need to give an explicit type to the binding when you use map_e!
, because
it relies on knowing what type it should coerce the values to.
Also, only values and not keys can be trait objects, because keys must
implement the Hash
trait, which is not
object safe.
Where the trait bounds on generic type parameters of the collections allow trait objects,
macros for explicitly typed variants are provided.
The explicitly typed versions of the macros are indicated by an _e
suffix.